import React, { useEffect } from 'react';
import loadjs from 'loadjs';

const loadMap = () => {
  if (!loadjs.isDefined('bdmap')) {
    window.bdMapLoadPromise = new Promise((resolve) => {
      loadjs(
        'http://api.map.baidu.com/getscript?v=3.0&ak=BsdrrUSaPSIpADIRCQDUsdLjXqkD9BTQ',
        'bdmap',
        () => {
          resolve();
        },
      );
    });
  }
  return window.bdMapLoadPromise;
};

/**
 * 百度地图
 */
export default (props) => {
  const {
    id = 'bdmap',
    center: [centerLng, centerLat] = [116.404, 39.915],
    zoom = 11,
    style,
    onLoaded,
    mapRef,
  } = props;

  useEffect(() => {
    loadMap().then(() => {
      const { BMap } = window;
      const map = new BMap.Map(id);
      map.centerAndZoom(new BMap.Point(centerLng, centerLat), zoom);
      if (mapRef) {
        mapRef.current = map;
      }
      if (onLoaded) {
        onLoaded(map);
      }
    });
  }, []);

  return <div id={id} style={{ width: '100%', height: '100%', ...style }} />;
};
